package com.lyf.controller;

import com.google.common.util.concurrent.RateLimiter;
import com.lyf.service.OrderService;
import com.lyf.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("stock")
@Slf4j  //快速日志
@RestController
public class StockController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    //创建令牌桶实例
    private RateLimiter rateLimiter = RateLimiter.create(10);   //每秒放行10个请求

    //生成md5
    @RequestMapping("md5")
    public String getMd5(Integer id, Integer userid) {
        String md5 = null;
        try {
            md5 = orderService.getMd5(id,userid);
        } catch (Exception e) {
            e.printStackTrace();
            return "获取md5失败: " + e.getMessage();
        }
        return "获取md5信息: " + md5;
    }

    //控制层---------
    //令牌桶+乐观锁 + md5签名(hash接口隐藏) + 单用户访问频率限制
    @GetMapping("kill")
    public String killToken(Integer id, Integer userid, String md5) {
        //加入令牌桶限流
        if(!rateLimiter.tryAcquire(3,TimeUnit.SECONDS)){ // 2秒
            log.info("抛弃请求");
            return "抢购失败";
        }
        try{
            //单用户调用接口的频率限制
            int count = userService.saveUserCount(userid);
            log.info("用户截至该次访问次数为：[{}]", count);
            //进行调用次数判断
            boolean isBanned = userService.getUserCount(userid);
            if(isBanned == true) {
                log.info("购买失败，超过频率限制");
                return "购买失败，超过频率限制，访问你次数" + count;
            }
            //根据秒杀商品id去调用秒杀业务
            int orderId = orderService.kill(id, userid, md5);
            return "秒杀成功，订单id为：" + orderId;
        }catch (Exception e){
            e.printStackTrace();
            return e.getMessage();
        }
    }
}
